// pages/reservation/reservation.js
const util = require('../../utils/util')
const api = require('../../utils/api')
import { getAvailableSpaces, createReservation, getUserInfo } from '../../utils/request'
Page({
  data: {
    userInfo: {},
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1,
    days: [],
    selectedDates: [],
    requiredQuota: 0,
    parkingData: [], // 存储API返回的车位数据
    maxSpots: 80,
    isLoading: false,
    showRulesPopup: false,
    showErrorPopup: false, // 控制错误弹窗显示
    errorTitle: '错误提示', // 错误弹窗标题
    errorMessage: '', // 错误弹窗消息
    isLoadingParkingData: false,
    selectedQuarter: 'current', // 默认选择当前季度
    currentQuarterText: '', // 当季度文本
    nextQuarterText: '', // 下季度文本
    currentQuarter: 0, // 当前季度数值
    nextQuarter: 0, // 下季度数值
    currentQuarterMonths: [], // 当季度月份
    nextQuarterMonths: [], // 下季度月份
    isAfterQuarterLastThursday: false, // 是否过了季度最后一个周四
    nextQuarterFirstMonth: 0, // 下个季度的第一个月
    calendarHintClass: '', // 用于存储日历区域闪烁动画类
    showScrollTip: false, // 控制滚动提示的显示
    hasAddedFirstDate: false // 记录是否已经添加过第一个日期
  },

  onLoad: function () {
    // 检查是否已经登录
    const userInfo = wx.getStorageSync('userInfo')
    if (!userInfo || !userInfo.phone) {
      wx.redirectTo({
        url: '/pages/login/login'
      })
      return
    }

    // 计算当前季度和下个季度
    this.calculateQuarters()

    this.setData({ userInfo })

    // 获取最新的用户信息（包括额度数据）
    this.fetchUserInfo()

    // 获取当前日期，用于请求车位数据
    const today = new Date()
    const formattedDate = util.formatDate(today)

    // 首次加载时获取停车位数据
    this.fetchParkingAvailability(formattedDate).then(() => {
      // 获取成功后生成日历
      this.generateCalendar()
    })

    // 开发环境提示，直接显示调试信息
    console.log('预约页面调试信息:')
    console.log('- 可选择日期查看剩余车位')
    console.log('- 周一/周五消耗0.5次额度，周二至周四消耗1次额度')
    console.log('- 周六/周日不可预约')
    console.log('- 当日可以预约，但预约后不可取消')
    console.log('- 剩余额度低于需要消耗的额度时不能预约')
  },

  // 计算当前季度和下个季度的信息
  calculateQuarters: function () {
    const now = new Date()
    const currentYear = now.getFullYear()
    const currentMonth = now.getMonth() + 1

    // 确定当前季度
    const currentQuarter = Math.ceil(currentMonth / 3)

    // 确定下一个季度
    let nextQuarter = currentQuarter + 1
    let nextQuarterYear = currentYear

    if (nextQuarter > 4) {
      nextQuarter = 1
      nextQuarterYear++
    }

    // 计算下个季度的第一个月
    const nextQuarterFirstMonth = (nextQuarter - 1) * 3 + 1

    // 计算当前季度的最后一个月
    const currentQuarterLastMonth = currentQuarter * 3

    // 获取当前季度最后一个月的最后一个星期四
    const quarterLastThursday = util.getLastThursdayOfMonth(
      currentYear,
      currentQuarterLastMonth
    )

    // 判断今天是否已过当前季度最后一个月的最后一个星期四
    const isAfterQuarterLastThursday = now >= quarterLastThursday

    // 计算当季度月份范围
    const currentStartMonth = (currentQuarter - 1) * 3 + 1
    const currentEndMonth = currentQuarter * 3
    const currentQuarterMonths = []

    for (let i = currentStartMonth; i <= currentEndMonth; i++) {
      currentQuarterMonths.push(i)
    }

    // 计算下季度月份范围
    const nextStartMonth = (nextQuarter - 1) * 3 + 1
    const nextEndMonth = nextQuarter * 3
    const nextQuarterMonths = []

    for (let i = nextStartMonth; i <= nextEndMonth; i++) {
      nextQuarterMonths.push(i)
    }

    // 生成季度文本
    const currentQuarterText = `${currentStartMonth}-${currentEndMonth}月`
    const nextQuarterText = `${nextStartMonth}-${nextEndMonth}月`

    this.setData({
      currentQuarter,
      nextQuarter,
      nextQuarterYear,
      currentQuarterText,
      nextQuarterText,
      currentQuarterMonths,
      nextQuarterMonths,
      isAfterQuarterLastThursday,
      nextQuarterFirstMonth
    })

    // 调试输出
    console.log('当前季度:', currentQuarter)
    console.log('当季度最后一个月:', currentQuarterLastMonth)
    console.log('当季度最后一个月的最后一个周四:', quarterLastThursday)
    console.log('是否已过季度最后周四:', isAfterQuarterLastThursday)
    console.log('下个季度:', nextQuarter)
    console.log('下个季度第一个月:', nextQuarterFirstMonth)
  },

  // 切换预约季度
  switchQuarter: function (e) {
    const quarter = e.currentTarget.dataset.quarter

    if (quarter !== this.data.selectedQuarter) {
      this.setData({
        selectedQuarter: quarter,
        selectedDates: [], // 切换季度时清空已选日期
        requiredQuota: 0
      })

      // 重新生成日历
      this.generateCalendar()
    }
  },

  onShow: function () {
    // 刷新用户数据
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo && userInfo.phone) {
      this.setData({ userInfo })
      // 获取最新的用户信息（包括额度数据）
      this.fetchUserInfo()
    }
  },

  // 获取最新的用户信息
  fetchUserInfo: function () {
    getUserInfo().then((res) => {
      console.log('获取用户信息成功:', res)
      const userInfo = res.data
      // 更新本地存储
      wx.setStorageSync('userInfo', userInfo)
      // 更新页面数据
      this.setData({ userInfo })
    }).catch((err) => {
      console.error('获取用户信息失败:', err)
    })
  },

  // 获取停车位可用情况数据
  fetchParkingAvailability: function (startDate) {
    if (this.data.isLoadingParkingData) {
      return Promise.resolve() // 如果已经在加载中，直接返回
    }

    this.setData({ isLoadingParkingData: true })
    return getAvailableSpaces(startDate)
      .then((res) => {
        console.log('获取停车位数据响应:', res)
        this.setData({
          parkingData: res.data || []
        })
        console.log('获取停车位数据成功:', res.data)
      })
      .catch((err) => {
        console.error('获取停车位数据异常:', err)
        util.showToast('获取停车位数据失败，请重试')
      })
      .finally(() => {
        this.setData({ isLoadingParkingData: false })
      })
  },

  // 根据日期查找停车位数据
  findParkingDataByDate: function (dateStr) {
    const { parkingData } = this.data
    const data = parkingData.data.dates.find((item) => item.date === dateStr)
    return data
  },

  // 检查日期是否在所选季度内
  isDateInSelectedQuarter: function (dateObj) {
    const {
      selectedQuarter,
      currentQuarter,
      nextQuarter,
      currentQuarterMonths,
      nextQuarterMonths,
      nextQuarterYear
    } = this.data

    const dateYear = dateObj.getFullYear()
    const dateMonth = dateObj.getMonth() + 1

    if (selectedQuarter === 'current') {
      // 检查是否在当前季度内
      return (
        currentQuarterMonths.includes(dateMonth) &&
        dateYear === new Date().getFullYear()
      )
    } else {
      // 检查是否在下个季度内
      if (nextQuarter === 1 && nextQuarterYear > new Date().getFullYear()) {
        // 下个季度是下一年的第一季度
        return (
          nextQuarterMonths.includes(dateMonth) && dateYear === nextQuarterYear
        )
      } else {
        // 下个季度是今年的季度
        return (
          nextQuarterMonths.includes(dateMonth) &&
          dateYear === new Date().getFullYear()
        )
      }
    }
  },

  // 生成日历数据
  generateCalendar: function () {
    try {
      const { year, month, selectedDates, parkingData, selectedQuarter } =
        this.data

      // 获取当月第一天是星期几 (调整为周一为第一天: 0=周一, 1=周二, ..., 6=周日)
      let firstDay = new Date(year, month - 1, 1).getDay() - 1
      if (firstDay === -1) firstDay = 6 // 如果是周日，调整为6

      // 获取当月有多少天
      const daysInMonth = new Date(year, month, 0).getDate()

      // 获取上个月有多少天
      const daysInLastMonth = new Date(year, month - 1, 0).getDate()

      // 生成日历数据
      let days = []

      // 当前日期，用于计算可预约性
      const today = new Date()
      const currentDate = new Date(
        today.getFullYear(),
        today.getMonth(),
        today.getDate()
      )

      // 计算当前年月
      const currentYear = today.getFullYear()
      const currentMonth = today.getMonth() + 1

      // 计算当前季度
      const currentQuarter = Math.ceil(currentMonth / 3)

      // 计算当前季度的最后一个月
      const currentQuarterLastMonth = currentQuarter * 3

      // 获取当前季度最后一个月的最后一个星期四
      const quarterLastThursday = util.getLastThursdayOfMonth(
        currentYear,
        currentQuarterLastMonth
      )

      // 判断今天是否已过当前季度最后一个月的最后一个星期四
      const isAfterQuarterLastThursday = today >= quarterLastThursday

      // 计算下个季度的第一个月
      const nextQuarter = (currentQuarter % 4) + 1
      const nextQuarterYear = nextQuarter === 1 ? currentYear + 1 : currentYear
      const nextQuarterFirstMonth = (nextQuarter - 1) * 3 + 1

      console.log('当前日期:', today)
      console.log('当前季度:', currentQuarter)
      console.log('当季度最后一个月:', currentQuarterLastMonth)
      console.log('当季度最后一个月的最后一个周四:', quarterLastThursday)
      console.log('是否已过季度最后周四:', isAfterQuarterLastThursday)
      console.log(
        '下个季度第一个月:',
        nextQuarterYear + '-' + nextQuarterFirstMonth
      )

      // 检查是否需要重新获取车位数据
      // 如果当前显示的月份是未来的月份，并且没有车位数据，则重新获取
      const shouldRefetchData =
        (year > today.getFullYear() ||
          (year === today.getFullYear() && month > today.getMonth() + 1)) &&
        !this.data.isLoadingParkingData &&
        (!parkingData || parkingData.length === 0)

      if (shouldRefetchData) {
        // 异步获取数据，不阻塞日历生成
        const firstDayOfMonth = new Date(year, month - 1, 1)
        const formattedDate = util.formatDate(firstDayOfMonth)
        this.fetchParkingAvailability(formattedDate).then(() => {
          // 获取成功后重新生成日历
          this.generateCalendar()
        })
      }

      // 上个月的最后几天
      for (let i = firstDay - 1; i >= 0; i--) {
        const prevMonthDate = new Date(year, month - 2, daysInLastMonth - i)
        const prevMonth = month === 1 ? 12 : month - 1
        const prevYear = month === 1 ? year - 1 : year
        const prevMonthStr = String(prevMonth).padStart(2, '0')
        const prevDayStr = String(daysInLastMonth - i).padStart(2, '0')
        const dateStr = `${prevYear}-${prevMonthStr}-${prevDayStr}`
        // 将星期几调整为：0=周一, 1=周二, ..., 6=周日
        let weekday = prevMonthDate.getDay() - 1
        if (weekday === -1) weekday = 6

        // 判断日期是否在所选季度内
        const isInSelectedQuarter = this.isDateInSelectedQuarter(prevMonthDate)

        // 判断是否可预约
        // 注意：上个月日期原则上不可预约，除非是特殊情况
        let isDateAvailable = false

        // 检查是否属于例外情况：季度最后一个月的最后一个周四之后，可以预约下个季度第一个月的日期
        // 且仅当选择的是"下季度预约"
        if (
          selectedQuarter === 'next' &&
          isAfterQuarterLastThursday &&
          prevMonthDate >= currentDate &&
          weekday !== 5 &&
          weekday !== 6 &&
          isInSelectedQuarter
        ) {
          // 检查是否是下个季度的第一个月
          const isPrevMonthNextQuarterFirstMonth =
            prevYear === nextQuarterYear && prevMonth === nextQuarterFirstMonth

          if (isPrevMonthNextQuarterFirstMonth) {
            isDateAvailable = true
          }
        }

        // 查找该日期的停车位数据
        const parkingInfo = this.findParkingDataByDate(dateStr)

        // 如果数据异常或不可预约，则设置为0
        let availableSpots = 0

        // 仅对可预约日期处理车位数据
        if (isDateAvailable && parkingInfo) {
          // 如果车位数据为null（异常数据），则该日期不可预约
          if (parkingInfo.availableSpots === null) {
            isDateAvailable = false
          } else {
            availableSpots = parkingInfo.availableSpots
          }
        }

        // 检查此日期是否已被选中
        const isSelected =
          selectedDates.findIndex((item) => item.date === dateStr) > -1

        days.push({
          day: daysInLastMonth - i,
          date: dateStr,
          type: 'other',
          available: isDateAvailable,
          selected: isSelected,
          weekday: weekday,
          availableSpots: availableSpots,
          isInSelectedQuarter: isInSelectedQuarter
        })
      }

      // 当月的天数
      for (let i = 1; i <= daysInMonth; i++) {
        const dateObj = new Date(year, month - 1, i)
        const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(
          i
        ).padStart(2, '0')}`

        // 将星期几调整为：0=周一, 1=周二, ..., 6=周日
        let weekday = dateObj.getDay() - 1
        if (weekday === -1) weekday = 6

        // 判断日期是否在所选季度内
        const isInSelectedQuarter = this.isDateInSelectedQuarter(dateObj)

        // 判断是否可预约
        // 1. 可以预约今天和未来日期 (修改为支持当日预约)
        // 2. 周六（5）和周日（6）不能预约
        // 3. 当前月可以预约
        // 4. 必须在所选季度内
        let isDateAvailable = false

        // 周末不可预约，必须在所选季度内
        if (
          dateObj >= currentDate &&
          weekday !== 5 &&
          weekday !== 6 &&
          isInSelectedQuarter
        ) {
          // 检查日期是否属于当前月
          const isCurrentMonthDate =
            year === currentYear && month === currentMonth

          // 检查是否属于例外情况：季度最后一个月的最后一个周四之后，可以预约下个季度第一个月的日期
          const isNextQuarterFirstMonthDate =
            year === nextQuarterYear && month === nextQuarterFirstMonth

          if (selectedQuarter === 'current' && isCurrentMonthDate) {
            // 当选择"当季度预约"时，只能预约当前月份的日期
            isDateAvailable = true
          } else if (
            selectedQuarter === 'next' &&
            isNextQuarterFirstMonthDate &&
            isAfterQuarterLastThursday
          ) {
            // 当选择"下季度预约"时，只能在季度最后一个月的最后一个周四之后预约下个季度第一个月的日期
            isDateAvailable = true
          }
        }

        // 查找该日期的停车位数据
        const parkingInfo = this.findParkingDataByDate(dateStr)

        // 如果数据异常或不可预约，则设置为0
        let availableSpots = 0

        // 仅对可预约日期处理车位数据
        if (isDateAvailable && parkingInfo) {
          // 如果车位数据为null（异常数据），则该日期不可预约
          if (parkingInfo.availableSpots === null) {
            isDateAvailable = false
          } else {
            availableSpots = parkingInfo.availableSpots
          }
        }

        // 检查此日期是否已被选中
        const isSelected =
          selectedDates.findIndex((item) => item.date === dateStr) > -1

        days.push({
          day: i,
          date: dateStr,
          type: 'current',
          available: isDateAvailable,
          selected: isSelected,
          isToday: util.isToday(dateObj),
          weekday: weekday,
          availableSpots: availableSpots,
          isInSelectedQuarter: isInSelectedQuarter
        })
      }

      // 下个月的前几天
      const daysAfter = 42 - days.length
      for (let i = 1; i <= daysAfter; i++) {
        const dateObj = new Date(year, month, i)
        const nextMonth = month === 12 ? 1 : month + 1
        const nextYear = month === 12 ? year + 1 : year
        const nextMonthStr = String(nextMonth).padStart(2, '0')
        const nextDayStr = String(i).padStart(2, '0')
        const dateStr = `${nextYear}-${nextMonthStr}-${nextDayStr}`
        // 将星期几调整为：0=周一, 1=周二, ..., 6=周日
        let weekday = dateObj.getDay() - 1
        if (weekday === -1) weekday = 6

        // 判断日期是否在所选季度内
        const isInSelectedQuarter = this.isDateInSelectedQuarter(dateObj)

        // 判断是否可预约
        // 下月日期原则上不可预约，除非是特殊情况
        let isDateAvailable = false

        // 检查是否属于例外情况：季度最后一个月的最后一个周四之后，可以预约下个季度第一个月的日期
        // 且仅当选择的是"下季度预约"
        if (
          selectedQuarter === 'next' &&
          isAfterQuarterLastThursday &&
          dateObj >= currentDate &&
          weekday !== 5 &&
          weekday !== 6 &&
          isInSelectedQuarter
        ) {
          // 检查是否是下个季度的第一个月
          const isNextQuarterFirstMonthDate =
            nextYear === nextQuarterYear && nextMonth === nextQuarterFirstMonth

          if (isNextQuarterFirstMonthDate) {
            isDateAvailable = true
          }
        }

        // 查找该日期的停车位数据
        const parkingInfo = this.findParkingDataByDate(dateStr)

        // 如果数据异常或不可预约，则设置为0
        let availableSpots = 0

        // 仅对可预约日期处理车位数据
        if (isDateAvailable && parkingInfo) {
          // 如果车位数据为null（异常数据），则该日期不可预约
          if (parkingInfo.availableSpots === null) {
            isDateAvailable = false
          } else {
            availableSpots = parkingInfo.availableSpots
          }
        }

        // 检查此日期是否已被选中
        const isSelected =
          selectedDates.findIndex((item) => item.date === dateStr) > -1

        days.push({
          day: i,
          date: dateStr,
          type: 'other',
          available: isDateAvailable,
          selected: isSelected,
          weekday: weekday,
          availableSpots: availableSpots,
          isInSelectedQuarter: isInSelectedQuarter
        })
      }

      this.setData({ days })
    } catch (error) {
      console.error('生成日历异常:', error)
      util.showToast('生成日历失败，请重试')
    }
  },

  // 选择日期
  selectDate: function (e) {
    try {
      const index = e.currentTarget.dataset.index
      const date = e.currentTarget.dataset.date
      const { days, selectedDates, selectedQuarter } = this.data

      // 检查日期是否可预约
      if (
        !days[index].available ||
        days[index].type !== 'current' ||
        days[index].availableSpots <= 0
      ) {
        if (!days[index].available) {
          if (!days[index].isInSelectedQuarter) {
            util.showToast(
              `该日期不在${
                selectedQuarter === 'current' ? '当前' : '下个'
              }季度内`
            )
          } else {
            util.showToast('该日期不可预约')
          }
        } else if (days[index].availableSpots <= 0) {
          util.showToast('该日期车位已满')
        }
        return
      }

      // 检查是否已经选择了这个日期
      const selectedIndex = selectedDates.findIndex(
        (item) => item.date === date
      )

      if (selectedIndex > -1) {
        // 已选择，取消选择
        selectedDates.splice(selectedIndex, 1)
        days[index].selected = false
      } else {
        // 未选择，添加到选择列表
        const dateObj = new Date(date)
        // 将星期几调整为：0=周一, 1=周二, ..., 6=周日
        let weekday = dateObj.getDay() - 1
        if (weekday === -1) weekday = 6

        // 根据新星期几数组格式化日期
        const weekdayNames = ['一', '二', '三', '四', '五', '六', '日']
        const formattedDate = `${date.split('-')[1]}月${
          date.split('-')[2]
        }日 周${weekdayNames[weekday]}`

        // 检查是否是首次选择日期
        const isFirstSelection = selectedDates.length === 0

        selectedDates.push({
          date,
          formattedDate,
          weekday,
          timestamp: dateObj.getTime(), // 添加时间戳，用于排序
          quarter: selectedQuarter // 记录预约时的季度
        })
        days[index].selected = true

        // 按日期从早到晚排序
        selectedDates.sort((a, b) => {
          const dateA = new Date(a.date)
          const dateB = new Date(b.date)
          return dateA - dateB // 升序排列
        })

        // 如果是首次选择，显示滚动提示
        if (isFirstSelection && !this.data.hasAddedFirstDate) {
          this.setData({
            showScrollTip: true,
            hasAddedFirstDate: true
          })

          // 3秒后自动隐藏提示
          setTimeout(() => {
            this.setData({
              showScrollTip: false
            })
          }, 3000)
        }
      }

      this.setData({
        days,
        selectedDates
      })

      this.calculateRequiredQuota()
    } catch (error) {
      console.error('选择日期异常:', error)
      util.showToast('操作失败，请重试')
    }
  },

  // 计算需要消耗的额度
  calculateRequiredQuota: function () {
    try {
      const { selectedDates } = this.data
      let quota = 0

      selectedDates.forEach((item) => {
        const weekday = item.weekday
        // 使用工具类计算额度
        quota += util.calculateDayQuota(weekday)
      })

      this.setData({ requiredQuota: quota })
    } catch (error) {
      console.error('计算额度异常:', error)
      this.setData({ requiredQuota: 0 })
    }
  },

  // 移除已选日期
  removeDate: function (e) {
    try {
      const index = e.currentTarget.dataset.index
      const { selectedDates, days } = this.data

      // 找到对应天在days中的索引
      const dateToRemove = selectedDates[index].date
      const dayIndex = days.findIndex((item) => item.date === dateToRemove)

      if (dayIndex > -1) {
        days[dayIndex].selected = false
      }

      selectedDates.splice(index, 1)

      this.setData({
        selectedDates,
        days
      })

      this.calculateRequiredQuota()
    } catch (error) {
      console.error('移除日期异常:', error)
      util.showToast('操作失败，请重试')
    }
  },

  // 切换到上个月
  prevMonth: function () {
    try {
      let { year, month } = this.data

      if (month === 1) {
        year--
        month = 12
      } else {
        month--
      }

      this.setData({
        year,
        month
      })

      // 检查是否需要更新车位数据
      const firstDayOfMonth = new Date(year, month - 1, 1)
      const today = new Date()

      // 如果查看的是未来月份，并且没有足够的车位数据，则重新获取
      if (firstDayOfMonth > today && this.data.parkingData.length === 0) {
        const formattedDate = util.formatDate(firstDayOfMonth)
        this.fetchParkingAvailability(formattedDate).then(() => {
          this.generateCalendar()
        })
      } else {
        this.generateCalendar()
      }
    } catch (error) {
      console.error('切换月份异常:', error)
      util.showToast('操作失败，请重试')
    }
  },

  // 切换到下个月
  nextMonth: function () {
    try {
      let { year, month } = this.data

      if (month === 12) {
        year++
        month = 1
      } else {
        month++
      }

      this.setData({
        year,
        month
      })

      // 检查是否需要更新车位数据
      const firstDayOfMonth = new Date(year, month - 1, 1)
      const today = new Date()

      // 如果查看的是未来月份，并且没有足够的车位数据，则重新获取
      if (firstDayOfMonth > today && this.data.parkingData.length === 0) {
        const formattedDate = util.formatDate(firstDayOfMonth)
        this.fetchParkingAvailability(formattedDate).then(() => {
          this.generateCalendar()
        })
      } else {
        this.generateCalendar()
      }
    } catch (error) {
      console.error('切换月份异常:', error)
      util.showToast('操作失败，请重试')
    }
  },

  // 导航到个人中心
  navigateToProfile: function () {
    wx.navigateTo({
      url: '/pages/profile/profile'
    })
  },

  // 提交预约
  submitReservation: function () {
    const {
      selectedDates,
      userInfo,
      requiredQuota,
      selectedQuarter,
      isLoading
    } = this.data

    // 防止重复提交
    if (isLoading) {
      return
    }

    if (selectedDates.length === 0) {
      util.showToast('请从日历中选择至少一个预约日期', 'none', 2500)
      // 添加视觉提示，让日历区域闪烁提示
      this.showCalendarHint()
      return
    }

    // 检查所选季度的额度是否足够
    const availableQuota =
      selectedQuarter === 'current'
        ? userInfo.current_quarter_quota_remaining
        : userInfo.next_quarter_quota_remaining || 0

    console.log('额度检查详情:', {
      selectedQuarter,
      userInfo: {
        current_quarter_quota_remaining: userInfo.current_quarter_quota_remaining,
        next_quarter_quota_remaining: userInfo.next_quarter_quota_remaining,
        current_quarter_quota: userInfo.current_quarter_quota,
        next_quarter_quota: userInfo.next_quarter_quota
      },
      availableQuota,
      requiredQuota,
      isEnough: availableQuota >= requiredQuota
    })

    if (availableQuota < requiredQuota) {
      util.showToast(
        `${
          selectedQuarter === 'current' ? '当季' : '下季'
        }预约额度不足，需要${requiredQuota}额度，当前可用${availableQuota}额度`,
        'none',
        3000
      )
      return
    }

    this.setData({ isLoading: true })

    // 显示加载提示
    wx.showLoading({
      title: '提交中...',
      mask: true
    })

    // 准备要提交的数据
    const requestData = {
      // phone: userInfo.phone,
      dates: selectedDates.map((item) => item.date)
    }
    console.log('requestData', requestData)
    createReservation(requestData)
      .then((res) => {
        console.log('预约成功响应:', res)
        // 显示API返回的消息
        util.showToast(res.message || '预约成功', 'success')
        // 清空已选日期
        this.setData({ 
          selectedDates: [],
          requiredQuota: 0,
          isLoading: false 
        })
        // 刷新用户信息
        this.fetchUserInfo()
        wx.hideLoading()
        
        // 预约成功后跳转到我的预约页面
        setTimeout(() => {
          wx.navigateTo({
            url: '/pages/profile/profile'
          })
        }, 1500) // 延迟1.5秒跳转，让用户看到成功提示
      })
      .catch((err) => {
        console.error('预约异常:', err)
        this.setData({ 
          showErrorPopup: true,
          errorTitle: '预约失败',
          errorMessage: err.message || '预约失败，请稍后再试',
          isLoading: false 
        })
        wx.hideLoading()
      })
  },

  // 显示预约规则弹窗
  showRules: function () {
    this.setData({
      showRulesPopup: true
    })
  },

  // 关闭规则弹窗
  onRulesClose: function () {
    this.setData({
      showRulesPopup: false
    })
  },

  // 关闭错误弹窗
  onErrorClose: function () {
    this.setData({
      showErrorPopup: false,
      errorMessage: ''
    })
  },

  // 添加视觉提示，让日历区域闪烁提示
  showCalendarHint: function () {
    // 添加震动效果
    if (wx.vibrateShort) {
      wx.vibrateShort()
    }

    // 获取日历卡片元素并添加闪烁动画类
    const query = wx.createSelectorQuery()
    query.select('.calendar-card').boundingClientRect()
    query.exec((res) => {
      if (res && res[0]) {
        // 使用视图动画添加闪烁效果
        this.setData({
          calendarHintClass: 'calendar-hint-animation'
        })

        // 2秒后移除闪烁动画类
        setTimeout(() => {
          this.setData({
            calendarHintClass: ''
          })
        }, 2000)
      }
    })
  },

  // 滚动到已选日期区域
  scrollToSelectedDates: function () {
    // 隐藏提示
    this.setData({
      showScrollTip: false
    })

    // 滚动到已选日期区域
    wx.createSelectorQuery()
      .select('.selected-dates-card')
      .boundingClientRect((rect) => {
        if (rect) {
          wx.pageScrollTo({
            scrollTop: rect.top,
            duration: 300
          })
        }
      })
      .exec()
  }
})
